package org.easypool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DataSource {

    private Logger logger = LoggerFactory.getLogger(DataSource.class);

    private String url;
    private String driverName;
    private String username;
    private String password;

    protected DataSource(DataSourceConfig dataSourceConfig) {

        this.url = dataSourceConfig.getUrl();
        this.driverName = dataSourceConfig.getDriverName();
        this.username = dataSourceConfig.getUsername();
        this.password = dataSourceConfig.getPassword();

        try {
            Class.forName(driverName);
            logger.info("onload driver class success!");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            logger.error("onload driver class fail:{}", e.getMessage());
        }

    }


    protected Connection getConnection() throws SQLException {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
            logger.info("get connection success:{}", connection);
        } catch (SQLException e) {
            e.printStackTrace();
            logger.error("connection fail:{}", e.getMessage());
        } finally {
            return connection;
        }
    }

}
